package br.com.wai2008.client.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Date;

import br.com.wai2008.client.configurations.ClientConfigurations;
import br.com.wai2008.client.dataobject.WAILocalizationObject;
import br.com.wai2008.client.dataobject.WAIServiceObject;
import br.com.wai2008.client.protocol.ApplyProtocol;
import br.com.wai2008.client.serial.HDSerialNumber;
import br.com.wai2008.client.sintetizer.VoiceSintetizer;
import br.com.wai2008.client.wireless.WirelessSignal;
import br.com.wai2008.socket.client.SocketClient;

public class ServiceWAI {

	public WAIServiceObject obterRota(String target, WAILocalizationObject object, int floor, 
			int restriction, String language, boolean simulation) {
		WAIServiceObject dataObject = null;
		try {
			String message = this.buildMessage(target, object, floor, restriction, language, simulation);
			if (message != null) {
				SocketClient socketClient = new SocketClient(ClientConfigurations.SERVER_HOST, 
						ClientConfigurations.SERVER_PORT, ClientConfigurations.REQUEST_TIMEOUT);
				socketClient.startConnection();
				System.out.println("DEBUG " + new Date().getMinutes() + ":" + new Date().getSeconds());
				socketClient.sendMessage(message);
				String serverResponse = socketClient.receiveMessage();
				dataObject = this.buildDataObject(serverResponse);
				System.out.println("DEBUG " + new Date().getMinutes() + ":" + new Date().getSeconds());
				if (dataObject.getMessage() != null) {
					VoiceSintetizer.read(language, dataObject.getMessage());
				}				
			} else {
				System.out.println("[ServiceThread] ERROR: Cannot build message");
			}
		} catch (UnknownHostException e) {
			System.out.println("[ServiceThread] ERROR: Server not found");
			e.printStackTrace();
		} catch (SocketTimeoutException e) { 
			System.out.println("[ServiceThread] ERROR: Timeout while waiting response message");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("[ServiceThread] ERROR: Failed to send message");
			e.printStackTrace();
		}
		return dataObject;
	}

	private String buildMessage(String target, WAILocalizationObject object, int floor, int restriction, String language, 
									boolean simulation) {
		BufferedReader brHDNumber = HDSerialNumber.getSerial();
		if (simulation) {
			return ApplyProtocol.buildSimulationMessage(brHDNumber, object, target, restriction, language);
		} else {
			BufferedReader brIwlist = WirelessSignal.getSignal();
			return ApplyProtocol.buildMessage(brHDNumber, brIwlist, target, floor, restriction, language);
		}
	}
	
	private WAIServiceObject buildDataObject(String message) {
		return ApplyProtocol.buildDataObject(message);
	}
}
